#ifndef MAIN_CPP_
#define MAIN_CPP_

#include <cstdio>
#include <cstdlib>

#include "ImageWindow.h"
#include "OpenGLImage.h"
#include "GL/glut.h"
#include <ctime>

using namespace std;

ImageWindow* window;
int WIDTH = 512, HEIGHT = 512;

void displayFunc() {
	static int frame = 1;
	static clock_t start = clock();
	window->draw();
	glutSwapBuffers();
	if (frame >= 1000) {
		clock_t end = clock();
		end = end - start;
		double sec = (double) (end) / CLOCKS_PER_SEC;
		char buffer[1024];
		sprintf(buffer, "FPS: %f", frame / sec);
		glutSetWindowTitle(buffer);
		frame = 0;
		start = clock();
	}
	++frame;
}

void mouseFunc(int button, int state, int x, int y) {
	window->mouseFunc(button, state, x, HEIGHT - y);
	glutPostRedisplay();
}

void motionFunc(int x, int y) {
	window->motionFunc(x, HEIGHT - y);
	glutPostRedisplay();
}

void timerFunc(int value) {
	window->incrFrame();
	glutTimerFunc(value, timerFunc, value);
}

void idleFunc() {
	glutPostRedisplay();
}

void passiveMotionFunc(int x, int y) {
	printf("%5i %5i\n", x, y);
}

int main(int argc, char** argv) {
	if (argc != 5) {
		fprintf(stderr,
				"Two images and 2 frame numbers must be specified at the command line.");
		return -1;
	}

	OpenGLImage* start, *end;
	int dynamicFrames, staticFrames;

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
	glutInitWindowPosition(100, 100);
	glutInitWindowSize(WIDTH, HEIGHT);
	glutCreateWindow("FPS: 0000.000000");

	start = new OpenGLImage(argv[1]);
	end = new OpenGLImage(argv[2]);
	dynamicFrames = atoi(argv[3]);
	staticFrames = atoi(argv[4]);

	if (start->getWidth() != end->getWidth() || start->getHeight()
			!= end->getHeight()) {
		fprintf(stderr, "The two images specified must be the same size.");
		return -1;
	}

	window = new ImageWindow(start, end, dynamicFrames, staticFrames);
	window->init();

	glutDisplayFunc(displayFunc);
	glutMouseFunc(mouseFunc);
	glutMotionFunc(motionFunc);
	//glutPassiveMotionFunc(passiveMotionFunc);
	glutTimerFunc(2000 / dynamicFrames, timerFunc, 2000 / dynamicFrames);
	glutIdleFunc(idleFunc);

	glutMainLoop();
	return 0;
}

#endif
